package com.nifostasky.comic.common.tokenfilter;


import com.nifostasky.comic.common.threadlocal.LocalData;
import com.nifostasky.comic.common.threadlocal.SessionLoad;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 *
 *用户session操作类，针对 ThreadLocal 操作二次封装
 * @author : Administrator
 * @date : 2021/8/18 14:45
 *
 */
@Component
@Slf4j
public class LocalDataControl {
    //定义 存储用户信息的 session属性名
    public static final String SESSION_USERPROFILE = "localData";

    /**
     * 更新用户信息到session中 , 并将当前用户信息绑定当前线程;
     */
    public static void setLocalData(LocalData localData) {
        if (Objects.isNull(localData)) {
            log.error("用户信息不能为空,线程绑定用户信息失败");
            return;
        }
        //将用户信息存储到session中
        HttpSession session = getSession();
        session.setAttribute(SESSION_USERPROFILE, localData);
        //将当前用户信息绑定当前线程;
        SessionLoad.setLocalData(localData);
    }

    /**
     * 移除用户 :移除session,移除线程绑定对象
     */
    public static void removeLocalData(){
        HttpSession session = getSession();
        //移除session
        session.removeAttribute(SESSION_USERPROFILE);
        //移除线程绑定对象
        SessionLoad.removeLocalData();
    }

    /**
     * 获取当前 Request
     */
    private static HttpSession getSession() {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
        return session;
    }
}
